package org.java.user.controller;

import org.java.commons.vo.Result;
import org.java.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/changePassword")
public class ChangePasswordController {

    @Autowired
    public UserService userService;

    @GetMapping
    public String changePassword(){
        return "changePassword";
    }

    @PostMapping
    public ModelAndView changePassword(@AuthenticationPrincipal OAuth2Authentication authentication,
                                       @RequestParam("oldPassword") String oldPassword,
                                       @RequestParam("newPassword")String newPassword,
                                       @RequestParam("confirmPassword")String confirmPassword){
        //需要把这些参数传到json页面
        Result result = this.changePasswordJson(authentication,oldPassword,newPassword,confirmPassword);
        //（模型和视图）
        ModelAndView mav = new ModelAndView();
        if (result.getCode() == 1){
            //修改改成功
            mav.setViewName("redirect:./changPassword")     ;
        }else {
            //修改失败
            mav.setViewName("changePassword");
        }
        //把信息传到页面上
        mav.addObject("result",result);
    return mav;
    }

    @PostMapping(produces = "application/json")
    @ResponseBody
    private Result changePasswordJson(@AuthenticationPrincipal OAuth2Authentication authentication,
                                      @RequestParam("oldPassword") String oldPassword,
                                      @RequestParam("newPassword")String newPassword,
                                      @RequestParam("confirmPassword")String confirmPassword) {
        //根据用户名去获取用户，才能知道是哪个用户修改的密码
        String id = authentication.getName();
        return userService.changePassword(id,oldPassword,newPassword,confirmPassword);
}

}
